<template>
  <div class="bpmn-com containers">
    <div class="loading" v-if="loading">Loading...</div>
    <template v-else>
      <!-- 画布区域 -->
      <div class="canvas" ref="canvas"></div>

      <!-- 侧边栏区域 -->
      <div class="panel" ref="properties"></div>
    </template>
  </div>
</template>

<script>
import axois from "axios";
import {
  BpmnPropertiesPanelModule, // 基础侧边栏渲染入口
  BpmnPropertiesProviderModule, // 侧边栏属性编辑表单构造器
} from "bpmn-js-properties-panel";
import BpmnModeler from "bpmn-js/lib/Modeler";
import camundaModdleDescriptor from "camunda-bpmn-moddle/resources/camunda";
import axios from "axios";
export default {
  name: "AxiosBpmn",
  data() {
    return {
      bpmnModeler: null,
      canvas: null,
      loading: true,
      xmlUrlAdress: "",
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    async init() {
      this.loading = true;
      this.xmlUrlAdress = await this.getXnlUrl();
      this.loading = false;
      this.$nextTick(() => {
        this.initBpmn();
      });
    },
    getXnlUrl() {
      return new Promise((res) => {
        setTimeout(() => {
          const url = "http://localhost:1256/newBpmn";
          res(url);
        }, 1000);
      });
    },
    initBpmn() {
      this.canvas = this.$refs.canvas;
      this.bpmnModeler = new BpmnModeler({
        container: this.canvas,
        keyboard: { bindTo: document },
        propertiesPanel: {
          parent: this.$refs["properties"], // 侧边栏挂载的 Dom Id
        },
        // 添加到扩展模块内
        additionalModules: [
          BpmnPropertiesPanelModule,
          BpmnPropertiesProviderModule,
        ],
        moddleExtensions: {
          camunda: camundaModdleDescriptor,
        },
      });
      this.createNewDiagram(this.xmlUrlAdress);
    },
    async createNewDiagram(xml) {
      const _self = this;
      let bpmnXmlStr = "";
      if (this.xmlUrlAdress === "") {
        bpmnXmlStr = this.defaultXmlStr;
        this.transformCanvas(bpmnXmlStr);
      } else {
        try {
          let res = await axios({
            method: "get",
            timeout: 2000,
            url: _self.xmlUrlAdress,
            headers: { "Content-Type": "multipart/form-data" },
          });
          bpmnXmlStr = res["data"];
          this.transformCanvas(bpmnXmlStr);
        } catch (e) {
          console.error("500: 服务器异常！", e)
        }
      }
    },
    transformCanvas(bpmnXmlStr) {
      try {
        this.bpmnModeler.importXML(bpmnXmlStr);

        // 让图能自动适应屏幕
        let canvas = this.bpmnModeler.get("canvas");
        canvas.zoom("fit-viewport");
      } catch (e) {
        console.log('err', e)
      }
    },
    success() {
      console.log("ok");
    },
  },
};
</script>

<style lang="scss" scoped>
.containers {
  position: absolute;
  background-color: #ffffff;
  width: 100%;
  height: 100%;
  .canvas {
    width: 100%;
    height: 100%;
  }
  .panel {
    position: fixed;
    right: 0;
    top: 0;
    width: 300px;
  }
}
</style>
